// FadeInView.js
import React, { Component } from 'react';
import {
    Animated,
    Easing,
    NativeModules,
} from 'react-native';

export default class TransformView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            mDefaultY:  props.defaultY,         // 默认值(默认在屏幕外,看不见)
            mDetalY:    props.detalY,           // 偏移量

            transY: new Animated.Value(0),      // Y轴
        };
    }

    componentWillMount(){
        console.log('this.mDefaultY'   + this.state.mDefaultY);
        console.log('this.detalY'     + this.props.detalY);
    }

    render() {
        return (
            <Animated.View
                style={{
                    transform: [
                        {
                            // y轴移动
                            translateY: this.state.transY.interpolate({
                                inputRange: [0, 1],
                                outputRange: [0, 0]
                            }),
                        },
                    ]
                }}>
                {this.props.children}
            </Animated.View>
        );
    }

    // 显示
    show() {
        // x、y:为视图的相对位置。width、height：为视图的宽度和高度。pageX、pageY为视图在屏幕上的绝对位置。
        NativeModules.measure(handle, (x, y, width, height, pageX, pageY) => {
            // 在屏幕里面，已显示
            if(pageY !== this.state.mDefaultY) return;

            this.setState({
                transY: new Animated.Value(0),
                mDetalY: this.props.detalY,
            });


            let timing = Animated.timing;
            Animated.parallel(['transY'].map(property => {
                return timing(this.state[property], {
                    toValue: 1,
                    duration: 2000,
                    easing: Easing.linear,
                });
            })).start();
        });
    }

    // 隐藏
    dismiss(){
        // x、y:为视图的相对位置。width、height：为视图的宽度和高度。pageX、pageY为视图在屏幕上的绝对位置。
        NativeModules.measure(handle, (x, y, width, height, pageX, pageY) => {
            // 在屏幕里面，已显示
            if(pageY === this.state.mDefaultY) return;

            this.setState({
                transY: new Animated.Value(0),
                mDetalY: - this.props.detalY,
            });

            let timing = Animated.timing;
            Animated.parallel(['transY'].map(property => {
                return timing(this.state[property], {
                    toValue: 1,
                    duration: 2000,
                    easing: Easing.linear,
                });
            })).start();
        });
    }
}